package com.bugsnag.ohos;

import com.bugsnag.ohos.internal.StateObserver;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * BaseObservable
 *
 * @since 2021-07-01
 */
public class BaseObservable {
    CopyOnWriteArrayList<StateObserver> observers = new CopyOnWriteArrayList<>();

    /**
     * Adds an observer that can react to [StateEvent] messages.
     */
    void addObserver(StateObserver observer) {
        observers.addIfAbsent(observer);
    }

    /**
     * Removes a previously added observer that reacts to [StateEvent] messages.
     *
     * @param observer
     */
    void removeObserver(StateObserver observer) {
        observers.remove(observer);
    }

    /**
     * This method should be invoked when the notifier's state has changed. If an observer
     * has been set, it will be notified of the [StateEvent] message so that it can react
     * appropriately. If no observer has been set then this method will no-op.
     *
     * @param event
     */
    void updateState(StateEvent event) {
        if (observers.isEmpty()) {
            return;
        }
        for (StateObserver observer : observers) {
            observer.onStateChange(event);
        }
    }
}
